
package com.zjff.myshop.front.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zjff.myshop.exception.BusinessException;
import com.zjff.myshop.front.pojo.form.DeleteOssFileForm;
import com.zjff.myshop.util.AliyunOSSUtil;
import com.zjff.myshop.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;

@Slf4j
@CrossOrigin
@RestController
@Api(value = "v1", tags = "08.对象存储Web接口")
@RequestMapping("/app/v1/oss")
public class OSSController {
    @Resource
    private AliyunOSSUtil ossUtil;

    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "上传文件", notes = "上传文件到阿里云OSS")
    @ApiImplicitParam(name = "file", value = "文件", dataType = "MultipartFile", required = true)
    @SaCheckLogin
    @PostMapping("/uploadFile")
    public Result uploadFile(MultipartFile file, String dir) {
        log.info(dir);

        if (file == null || file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }
        try {
            String path = "upload/" + dir + "/"; //TODO 此处应该有path路径赋值
            HashMap map = ossUtil.uploadFile(file, path);
            return Result.ok(map);
        } catch (IOException e) {
            log.error("文件上传到阿里云OSS错误", e);
            throw new BusinessException("文件上传错误");
        }
    }

    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "删除文件", notes = "删除阿里云OSS文件")
    @ApiImplicitParam(name = "form", value = "参数", dataType = "DeleteOssFileForm", required = true)
    @SaCheckLogin
    @PostMapping("/deleteFile")
    public Result deleteFile(@RequestBody DeleteOssFileForm form) {
        ossUtil.deleteFile(form.getPathes());
        return Result.ok("成功删除阿里云OSS文件！");
    }

}
